<template>
  <div class="create-question-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>创建题目</span>
      </div>

      <el-form ref="questionForm" :model="form" :rules="rules" label-width="100px" class="question-form">

        <el-form-item label="题目内容" prop="topic">
          <el-input v-model="form.topic" type="textarea" :rows="3" placeholder="请输入题目内容" />
        </el-form-item>

        <el-form-item label="题目类别" prop="question_type_id">
          <el-select v-model="form.question_type_id" placeholder="请选择题目类别" style="width: 100%;">
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目类型" prop="type_id">
          <el-select v-model="form.type_id" placeholder="请选择题目类型" style="width: 100%;">
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目选项" required>
          <div
            v-for="(option, index) in form.answer"
            :key="index"
            class="option-item"
          >
            <el-input
              v-model="option.content"
              :placeholder="`选项 ${getOptionLetter(index)} 内容`"
              :disabled="form.type_id === 3"
              style="flex: 1"
            />
            <el-button
              v-if="form.type_id !== 3"
              type="danger"
              icon="el-icon-delete"
              circle
              style="margin-left: 10px"
              @click="removeOption(index)"
            />
          </div>
          <el-button
            v-if="form.type_id !== 3"
            type="primary"
            plain
            icon="el-icon-plus"
            style="margin-top: 5px"
            @click="addOption"
          >
            添加选项
          </el-button>
        </el-form-item>

        <el-form-item label="正确答案" prop="answer_index">
          <el-select
            v-if="form.type_id === 1 || form.type_id === 3"
            v-model="form.answer_index"
            placeholder="请选择正确答案"
            style="width: 100%;"
          >
            <el-option
              v-for="(option, index) in form.answer"
              :key="index"
              :label="getOptionLetter(index) + '. ' + option.content"
              :value="index"
            />
          </el-select>

          <el-select
            v-if="form.type_id === 2"
            v-model="form.answer_index"
            multiple
            placeholder="请选择正确答案（可多选）"
            style="width: 100%;"
          >
            <el-option
              v-for="(option, index) in form.answer"
              :key="index"
              :label="getOptionLetter(index) + '. ' + option.content"
              :value="index"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="submitForm">立即创建</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createQuestion, getTpyeId } from '@/api/question'
import { Message, MessageBox } from 'element-ui'

export default {
  data() {
    return {
      form: {
        topic: '',
        question_type_id: null,
        type_id: null,
        answer: [{ content: '' }],
        answer_index: null
      },
      rules: {
        topic: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
        question_type_id: [{ required: true, message: '请选择题目类别', trigger: 'change' }],
        type_id: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
        answer_index: [{ required: true, message: '请选择正确答案', trigger: 'change' }]
      },
      categoryList: [],
      typeList: [
        { id: 1, name: '单选题' },
        { id: 2, name: '多选题' },
        { id: 3, name: '判断题' }
      ]
    }
  },
  watch: {
    'form.type_id'(newVal, oldVal) {
      this.$refs.questionForm.clearValidate('answer_index')

      if (newVal === 2) {
        this.form.answer_index = []
      } else {
        this.form.answer_index = null
      }

      if (newVal === 3) {
        this.form.answer = [{ content: '正确' }, { content: '错误' }]
      } else if (oldVal === 3) {
        this.form.answer = [{ content: '' }]
      }
    }
  },
  mounted() {
    getTpyeId().then(res => {
      if (res.code === 200) {
        this.categoryList = res.data
      }
    })
  },
  methods: {
    submitForm() {
      this.$refs.questionForm.validate(async(valid) => {
        if (!valid) return

        if (this.form.answer.some(option => !option.content)) {
          Message.error('所有选项内容都不能为空！')
          return
        }

        if (this.form.type_id === 2 && this.form.answer_index.length < 2) {
          Message.error('多选题至少需俩个正确答案！')
          return
        }

        try {
          // let answerIndexStr
          // if (Array.isArray(this.form.answer_index)) {
          //   answerIndexStr = this.form.answer_index.join(',') // 多选: "1,2"
          // } else if (this.form.answer_index !== null) {
          //   answerIndexStr = String(this.form.answer_index) // 单选/判断: "1"
          // } else {
          //   answerIndexStr = ''
          // }

          const answerIndexArray = Array.isArray(this.form.answer_index)
            ? this.form.answer_index
            : (this.form.answer_index !== null ? [this.form.answer_index] : [])

          const payload = {
            ...this.form,
            // answer_index: answerIndexStr,
            answer_index: JSON.stringify(answerIndexArray),
            answer: JSON.stringify(this.form.answer)
          }
          console.log('提交的 payload:', payload)
          const res = await createQuestion(payload)

          if (res.code === 200) {
            Message.success('题目创建成功！')
            this.resetForm()
            MessageBox.confirm('是否立即查看新创建的题目？', '题目创建成功', {
              confirmButtonText: '立即查看',
              cancelButtonText: '稍后',
              type: 'success'
            }).then(() => {
              this.$router.push('/question/list')
            }).catch(() => {
              console.log('取消查看新创建的题目')
            })
          } else {
            Message.error(res.message || '创建失败')
          }
        } catch (error) {
          Message.error('创建失败，请检查网络或稍后再试。')
          console.error('创建失败:', error)
        }
      })
    },
    resetForm() {
      this.$refs.questionForm.resetFields()
      this.form.answer = [{ content: '' }]
      this.form.answer_index = null
    },
    addOption() {
      const hasEmptyOption = this.form.answer.some(option => option.content === '')
      if (hasEmptyOption) {
        Message.warning('请先填写所有已存在的选项内容！')
        return
      }
      this.form.answer.push({ content: '' })
    },
    removeOption(index) {
      if (this.form.answer.length <= 1) {
        Message.warning('至少需要一个选项')
        return
      }

      this.form.answer.splice(index, 1)

      const isMultiple = Array.isArray(this.form.answer_index)
      if (isMultiple) {
        const newAnswerIndex = this.form.answer_index
          .filter(i => i !== index)
          .map(i => (i > index ? i - 1 : i))
        this.form.answer_index = newAnswerIndex
      } else {
        // 单选模式
        if (this.form.answer_index === index) {
          this.form.answer_index = null
        } else if (this.form.answer_index > index) {
          this.form.answer_index--
        }
      }
    },
    getOptionLetter(index) {
      return String.fromCharCode(65 + index)
    }
  }
}
</script>

<style scoped>
.create-question-container {
  padding: 20px;
}
.question-form {
  max-width: 600px;
}
.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.form-actions {
  display: flex;
  gap: 10px;
}
</style>
